//
// Created by liule on 2021/8/12.
//

#include "Snake.h"

Snake::Snake(Wall *wall):wall(wall) {

    pHead = NULL;

    addPoint(3 , 3);
    addPoint(4 , 3);

    cout << "Snake init" << endl;

}


void Snake::addPoint(int x, int y) {

    Point *newPoint = new Point;
    newPoint->x = x;
    newPoint->y = y;
    newPoint->next = NULL;

    Point *temp = pHead;
    while (temp != NULL) {
        wall->changeGameArr(temp->x, temp->y, '=');
        temp = temp->next;
    }

    newPoint->next = pHead;
    pHead = newPoint;
    wall->changeGameArr(pHead->x, pHead->y, '@');

}

void Snake::deleteEndPoint() {

    Point *tempPoint = pHead;
    Point *endPoint = NULL;

    if(tempPoint == NULL || tempPoint->next == NULL) {
        return;
    }
    while (tempPoint->next != NULL) {
        if(tempPoint->next->next == NULL) {
            endPoint = tempPoint->next;
            tempPoint->next = NULL;
            break;
        }
        tempPoint = tempPoint->next;
    }
    if(endPoint != NULL) {
        wall->changeGameArr(endPoint->x, endPoint->y, ' ');
        delete endPoint;
    }

}

void Snake::destorySnake() {

    Point *pTemp = NULL;
    while (pHead != NULL) {
        pTemp = pHead->next;
        delete pHead;
        pHead = pTemp;
    }

}

Snake::~Snake() {

    destorySnake();
    cout << "delete Snake init" << endl;

}
